namespace Imps.Client.Pc
{
    using System.Drawing;
    using System.IO;
    using System.Xml;
    using Imps.Client;
    using Imps.Common;
    using Imps.Utils;

    public class PersistentManager : IPersistentManager
    {
        private string _dirHistory;
        private string _dirImps;
        private string _dirMyContactPortrait;
        private string _dirMyUsedGroupPortrait;
        private string _dirMyUsedPortrait;
        private string _dirWin;
        private IFrameworkWindow _host;
        private string _pathCfgImps;
        private string _pathCfgWnd;
        private string _pathContacts;
        private string _pathPermissions;
        private string _pathPersonalGroups;
        private string _pathPGroupCategorys;
        private string _pathPlugins;
        private string _pathRecentBuddies;
        private string _pathScheduleSms;
        private string _pathUserInfo;
        private object _syncObjCfgImps = new object();
        private object _syncObjCfgWnd = new object();
        private object _syncObjContacts = new object();
        private object _syncObjPermissions = new object();
        private object _syncObjPlugins = new object();
        private object _syncObjPortraits = new object();
        private object _syncObjRecentBuddies = new object();
        private object _syncObjUserInfo = new object();
        private object _syncPgroups = new object();
        private object _syncScheduleSms = new object();
        private long _userId;
        private const string XA_StoreMode = "StoreMode";
        private const string XN_RootConfig = "ImpsConfiguration";
        private const string XN_SystemConfig = "SystemConfiguration";
        private const string XN_UserConfig = "UserConfiguration";

        public PersistentManager(IFrameworkWindow host)
        {
            //this._host = host;
            //this._dirWin = FilePathHelper.GetPathWithEnvVar(@"%AppData%\" + AppDictionary.ShortEnglishName + @"\");
            //this._pathCfgWnd = this._dirWin + "configuration.dat";
            //this._pathPGroupCategorys = this._dirWin + "PGCategorys.dat";
        }

        private static string DecodeMode1(string text)
        {
            string str = string.Empty;
            try
            {
                str = GZipHelper.DecompressString(text);
            }
            catch
            {
                str = string.Empty;
            }
            if (!string.IsNullOrEmpty(str))
            {
                return str;
            }
            return text;
        }

        public void DelById(string userId)
        {
            //this.InnerDelSingleDir(Path.Combine(this._dirWin, userId));
        }

        public void DelChatHistoryById(string userId)
        {
            //this.InnerDelSingleFileById(userId, "history.dat");
        }

        public void DelContactsInfoById(string userId)
        {
            //this.InnerDelSingleFileById(userId, "contacts.dat");
        }

        public void DelPermissionById(string userId)
        {
            //this.InnerDelSingleFileById(userId, "permissions.dat");
        }

        public void DelPluginsCfgById(string userId)
        {
            //this.InnerDelSingleDir(this._dirWin + userId + @"\Plugins");
        }

        public void DelPortraitsById(string userId)
        {
            //this.InnerDelSingleDir(this._dirWin + userId + @"\Portraits");
        }

        public void DelUserCfgById(string userId)
        {
            //this.InnerDelSingleFileById(userId, "configuration.dat");
        }

        public void DelUserInfoById(string userId)
        {
            //this.InnerDelSingleFileById(userId, "userinfo.dat");
        }

        private void DoLoadData(PersistentDelegate load, string filename, string xpath, object syncObj)
        {
            //this.DoLoadData(load, filename, xpath, syncObj, true);
        }

        private void DoLoadData(PersistentDelegate load, string filename, string xpath, object syncObj, bool verify)
        {
            //try
            //{
            //    if (!string.IsNullOrEmpty(filename))
            //    {
            //        XmlNode section = this.GetXmlNodeFromFile(filename, xpath, syncObj);
            //        if (verify)
            //        {
            //            XmlNode node = section.SelectSingleNode("verify/info");
            //            if ((node == null) || (XmlHelper.ReadXmlAttributeDateTime(node, "datetime", DateTime.MinValue).AddDays(30.0).CompareTo(Imps.Client.Core.User.ServerTime) < 0))
            //            {
            //                return;
            //            }
            //        }
            //        load(section);
            //    }
            //}
            //catch (Exception exception)
            //{
            //    ClientLogger.WriteGeneral("加载本地缓存失败", string.Format("{0}\r\n{1}", filename, exception.Message), 10);
            //}
        }

        private void DoSaveData(PersistentDelegate save, string filename, string xpath, object syncObj)
        {
            //try
            //{
            //    if (!string.IsNullOrEmpty(filename))
            //    {
            //        XmlNode section = this.GetXmlNodeFromFile(filename, xpath, syncObj);
            //        save(section);
            //        XmlNode newChild = section.SelectSingleNode("verify/info");
            //        if (newChild != null)
            //        {
            //            newChild.Attributes["datetime"].Value = Imps.Client.Core.User.ServerTime.ToString("yyyy-MM-dd");
            //        }
            //        else
            //        {
            //            newChild = section.OwnerDocument.CreateNode(XmlNodeType.Element, "verify", null);
            //            newChild.InnerXml = "<info datetime='" + Imps.Client.Core.User.ServerTime.ToString("yyyy-MM-dd") + "' />";
            //            section.AppendChild(newChild);
            //        }
            //        XmlWriterSettings settings = new XmlWriterSettings();
            //        settings.Encoding = Encoding.UTF8;
            //        settings.CloseOutput = true;
            //        settings.Indent = true;
            //        settings.OmitXmlDeclaration = false;
            //        XmlNode documentElement = section.OwnerDocument.DocumentElement;
            //        string innerXml = documentElement.InnerXml;
            //        documentElement.InnerXml = EncodeMode1(innerXml);
            //        XmlHelper.SetNodeAttributeInt32(documentElement, "StoreMode", 1);
            //        if (!File.Exists(filename))
            //        {
            //            FilePathHelper.MakeSureFilePathExists(filename);
            //        }
            //        lock (syncObj)
            //        {
            //            using (XmlWriter writer = XmlWriter.Create(filename, settings))
            //            {
            //                section.OwnerDocument.Save(writer);
            //                writer.Flush();
            //                writer.Close();
            //            }
            //        }
            //    }
            //}
            //catch (Exception exception)
            //{
            //    ClientLogger.WriteGeneral("保存本地缓存失败", string.Format("{0}\r\n{1}", filename, exception.Message), 10);
            //}
        }

        private static string EncodeMode1(string text)
        {
            try
            {
                return GZipHelper.CompressString(text);
            }
            catch
            {
            }
            return string.Empty;
        }

        private XmlNode GetXmlNodeFromFile(string filename, string xpath, object syncObj)
        {
            XmlDocument document = new XmlDocument();
            XmlNode node = null;
            try
            {
                if (!File.Exists(filename))
                {
                    return node;
                }
                lock (syncObj)
                {
                    document.Load(filename);
                }
                XmlNode documentElement = document.DocumentElement;
                if (documentElement == null)
                {
                    return node;
                }
                XmlAttribute attribute = documentElement.Attributes["StoreMode"];
                if (attribute == null)
                {
                    return node;
                }
                if (attribute.Value == "1")
                {
                    string innerXml = documentElement.InnerXml;
                    documentElement.InnerXml = DecodeMode1(innerXml);
                    if (documentElement.FirstChild is XmlText)
                    {
                        documentElement.RemoveChild(documentElement.FirstChild);
                    }
                    return node;
                }
                documentElement.InnerXml = string.Empty;
            }
            catch
            {
            }
            finally
            {
                if (string.IsNullOrEmpty(xpath))
                {
                    node = document;
                }
                else
                {
                    node = XmlHelper.MakeSureChildPathExists(document, xpath);
                }
            }
            return node;
        }

        private void InnerDelSingleDir(string dir)
        {
            if (Directory.Exists(dir))
            {
                try
                {
                    Directory.Delete(dir, true);
                }
                catch
                {
                }
            }
        }

        private void InnerDelSingleFileById(string userId, string filename)
        {
            //string path = this._dirWin + userId + @"\" + filename;
            //if (File.Exists(path))
            //{
            //    try
            //    {
            //        File.Delete(path);
            //    }
            //    catch
            //    {
            //    }
            //}
        }

        public void LoadAccountsData(PersistentDelegate load)
        {
            //this.DoLoadData(load, this._pathCfgWnd, "ImpsConfiguration/AccountsData", this._syncObjCfgWnd, false);
        }

        public void LoadById(long userId)
        {
            //this._userId = userId;
            //this._dirImps = this._dirWin + userId.ToString() + @"\";
            //this._dirHistory = this._dirImps + @"History\";
            //this._dirMyContactPortrait = this._dirImps + @"Portraits\";
            //this._dirMyUsedPortrait = this._dirImps + @"MyPortraits\";
            //this._pathPlugins = this._dirImps + @"Plugins\";
            //this._dirMyUsedGroupPortrait = this._dirImps + @"GroupPortraits\";
            //this._pathCfgImps = this._dirImps + "configuration.dat";
            //this._pathUserInfo = this._dirImps + "userinfo.dat";
            //this._pathContacts = this._dirImps + "contacts.dat";
            //this._pathPermissions = this._dirImps + "permissions.dat";
            //this._pathPersonalGroups = this._dirImps + "PersonalGroups.dat";
            //this._pathScheduleSms = this._dirImps + "scheduleSms.dat";
            //this._pathRecentBuddies = this._dirImps + "recentBuddies.dat";
        }

        public void LoadContacts(PersistentDelegate load)
        {
            //this.DoLoadData(load, this._pathContacts, "ContactList", this._syncObjContacts);
        }

        public void LoadImpsUserConfig(PersistentDelegate load)
        {
            //this.DoLoadData(load, this._pathCfgImps, "ImpsConfiguration/UserConfiguration", this._syncObjCfgImps);
        }

        public void LoadPermissions(PersistentDelegate load)
        {
            //this.DoLoadData(load, this._pathPermissions, "permissions", this._syncObjPermissions);
        }

        public void LoadPersonalGroupCategorys(PersistentDelegate load)
        {
            //this.DoLoadData(load, this._pathPGroupCategorys, "PersonalGroups", this._syncPgroups);
        }

        public void LoadPersonalGroups(PersistentDelegate load)
        {
            //this.DoLoadData(load, this._pathPersonalGroups, "PersonalGroups", this._syncPgroups);
        }

        public void LoadPluginData(string pluginName, PersistentDelegate load)
        {
            //string filename = this._pathPlugins + pluginName + ".dat";
            //this.DoLoadData(load, filename, string.Empty, this._syncObjPlugins);
        }

        public Image LoadPortrait(IicUri uri, out int crc)
        {
            
            crc = 0;
            return null;
            //if ((uri == null) || !uri.IsValid)
            //{
            //    return null;
            //}
            //if ((this._host.AccountManager == null) || (this._host.AccountManager.CurrentUser == null))
            //{
            //    return null;
            //}
            //string path = this.BaseDirForPortrait + uri.ToUniqueString() + ".dat";
            //try
            //{
            //    MemoryStream stream;
            //    if (!File.Exists(path))
            //    {
            //        return null;
            //    }
            //    lock (this._syncObjPortraits)
            //    {
            //        using (FileStream stream2 = File.Open(path, FileMode.Open, FileAccess.Read, System.IO.FileShare.Read))
            //        {
            //            if (stream2.Length == 0L)
            //            {
            //                return null;
            //            }
            //            byte[] buffer = new byte[4];
            //            stream2.Read(buffer, 0, 4);
            //            crc = BitConverter.ToInt32(buffer, 0);
            //            byte[] buffer2 = new byte[stream2.Length - 4L];
            //            stream2.Read(buffer2, 0, buffer2.Length);
            //            stream2.Close();
            //            stream = new MemoryStream(buffer2);
            //        }
            //    }
            //    return Image.FromStream(stream);
            //}
            //catch (Exception exception)
            //{
            //    ClientLogger.WriteGeneral("加载本地头像失败", string.Format("{0}\r\n{1}", path, exception.Message), 10);
            //    crc = 0;
            //    return null;
            //}
        }

        public void LoadRecentBuddies(PersistentDelegate load)
        {
            //this.DoLoadData(load, this._pathRecentBuddies, "RecentBuddies", this._syncObjRecentBuddies);
        }

        public void LoadScheduleSmses(PersistentDelegate load)
        {
            //this.DoLoadData(load, this._pathScheduleSms, "ScheduleSms", this._syncScheduleSms);
        }

        public void LoadSubscribedServiceInfos(PersistentDelegate load)
        {
            //this.DoLoadData(load, this._pathUserInfo, "UserInfo/services", this._syncObjUserInfo);
        }

        public void LoadSystemConfig(PersistentDelegate load)
        {
            //this.DoLoadData(load, this._pathCfgImps, "ImpsConfiguration/SystemConfiguration", this._syncObjCfgImps);
        }

        public void LoadUserInfo(PersistentDelegate load)
        {
            //this.DoLoadData(load, this._pathUserInfo, "UserInfo/personal", this._syncObjUserInfo);
        }

        public void LoadWindowsUserCfg(PersistentDelegate load)
        {
            //this.DoLoadData(load, this._pathCfgWnd, "ImpsConfiguration/UserConfiguration", this._syncObjCfgWnd, false);
        }

        public void SaveContacts(PersistentDelegate save)
        {
            //if (this._host.AccountManager.CurrentUser.Configuration.UserSetting.SaveMyInfo)
            //{
            //    this.DoSaveData(save, this._pathContacts, "ContactList", this._syncObjContacts);
            //}
        }

        public void SaveImpsUserConfig(PersistentDelegate save)
        {
            //if (this._host.AccountManager.CurrentUser.Configuration.UserSetting.SaveMyInfo)
            //{
            //    this.DoSaveData(save, this._pathCfgImps, "ImpsConfiguration/UserConfiguration", this._syncObjCfgImps);
            //}
        }

        public void SaveLocalAccountsData(PersistentDelegate save)
        {
            //this.DoSaveData(save, this._pathCfgWnd, "ImpsConfiguration/AccountsData", this._syncObjCfgWnd);
        }

        public void SavePermissions(PersistentDelegate save)
        {
            //if (this._host.AccountManager.CurrentUser.Configuration.UserSetting.SaveMyInfo)
            //{
            //    this.DoSaveData(save, this._pathPermissions, "permissions", this._syncObjPermissions);
            //}
        }

        public void SavePersonalGroupCategorys(PersistentDelegate save)
        {
            //this.DoSaveData(save, this._pathPGroupCategorys, "PersonalGroups", this._syncPgroups);
        }

        public void SavePersonalGroups(PersistentDelegate save)
        {
            //if (this._host.AccountManager.CurrentUser.Configuration.UserSetting.SaveMyInfo)
            //{
            //    this.DoSaveData(save, this._pathPersonalGroups, "PersonalGroups", this._syncPgroups);
            //}
        }

        public void SavePluginData(string pluginName, PersistentDelegate save)
        {
            //if (this._host.AccountManager.CurrentUser.Configuration.UserSetting.SaveMyInfo)
            //{
            //    string filename = this._pathPlugins + pluginName + ".dat";
            //    this.DoSaveData(save, filename, string.Empty, this._syncObjPlugins);
            //}
        }

        public bool SavePortrait(IicUri uri, Image portrait, int crc)
        {
            return true;
            //try
            //{
            //    if (!this._host.AccountManager.CurrentUser.Configuration.UserSetting.SaveMyInfo)
            //    {
            //        return false;
            //    }
            //    if ((portrait == null) || (uri == null))
            //    {
            //        return false;
            //    }
            //    byte[] bytes = BitConverter.GetBytes(crc);
            //    if (!Directory.Exists(this.BaseDirForPortrait))
            //    {
            //        Directory.CreateDirectory(this.BaseDirForPortrait);
            //    }
            //    string path = this.BaseDirForPortrait + uri.ToUniqueString() + ".dat";
            //    lock (this._syncObjPortraits)
            //    {
            //        using (FileStream stream = File.Open(path, FileMode.Create, FileAccess.ReadWrite, System.IO.FileShare.Read))
            //        {
            //            stream.Write(bytes, 0, bytes.Length);
            //            portrait.Save(stream, ImageFormat.Jpeg);
            //            stream.Flush();
            //            stream.Close();
            //        }
            //    }
            //    return true;
            //}
            //catch
            //{
            //    return false;
            //}
        }

        public void SaveRecentBuddies(PersistentDelegate save)
        {
            //if (this._host.AccountManager.CurrentUser.Configuration.UserSetting.SaveMyInfo)
            //{
            //    this.DoSaveData(save, this._pathRecentBuddies, "RecentBuddies", this._syncObjRecentBuddies);
            //}
        }

        public void SaveScheduleSmses(PersistentDelegate save)
        {
            //if (this._host.AccountManager.CurrentUser.Configuration.UserSetting.SaveMyInfo)
            //{
            //    this.DoSaveData(save, this._pathScheduleSms, "ScheduleSms", this._syncScheduleSms);
            //}
        }

        public void SaveSubscribedServiceInfos(PersistentDelegate save)
        {
            //if (this._host.AccountManager.CurrentUser.Configuration.UserSetting.SaveMyInfo)
            //{
            //    this.DoSaveData(save, this._pathUserInfo, "UserInfo/services", this._syncObjUserInfo);
            //}
        }

        public void SaveSystemConfig(PersistentDelegate save)
        {
            //if (this._host.AccountManager.CurrentUser.Configuration.UserSetting.SaveMyInfo)
            //{
            //    this.DoSaveData(save, this._pathCfgImps, "ImpsConfiguration/SystemConfiguration", this._syncObjCfgImps);
            //}
        }

        public void SaveUserInfo(PersistentDelegate save)
        {
            //if (this._host.AccountManager.CurrentUser.Configuration.UserSetting.SaveMyInfo)
            //{
            //    this.DoSaveData(save, this._pathUserInfo, "UserInfo/personal", this._syncObjUserInfo);
            //}
        }

        public void SaveWindowsUserCfg(PersistentDelegate save)
        {
            //this.DoSaveData(save, this._pathCfgWnd, "ImpsConfiguration/UserConfiguration", this._syncObjCfgWnd);
        }

        public string BaseDirForCurrentPortrait
        {
            get
            {
                return "";// (this.BaseDirForPortrait + this.UserId.ToString() + ".dat");
            }
        }

        public string BaseDirForGroupPortrait
        {
            get
            {
                return this._dirMyUsedGroupPortrait;
            }
            set
            {
                this._dirMyUsedGroupPortrait = value;
            }
        }

        public string BaseDirForHistory
        {
            get
            {
                return this._dirHistory;
            }
            set
            {
                this._dirHistory = value;
            }
        }

        public string BaseDirForImps
        {
            get
            {
                return this._dirImps;
            }
        }

        public string BaseDirForMyUsedPortrait
        {
            get
            {
                return this._dirMyUsedPortrait;
            }
            set
            {
                this._dirMyUsedPortrait = value;
            }
        }

        public string BaseDirForPortrait
        {
            get
            {
                return this._dirMyContactPortrait;
            }
        }

        public string BaseDirForWindows
        {
            get
            {
                return this._dirWin;
            }
        }

        public string TempDir
        {
            get
            {
                return (this._dirWin + @"Temp\");
            }
        }

        public long UserId
        {
            get
            {
                return this._userId;
            }
        }
    }
}
